<?php

namespace App\HttpController\Web;

use AlibabaCloud\Client\AlibabaCloud;
use App\HttpController\BaseController;
use App\HttpController\ViewController;
use App\Model\FoodsModel;
use App\Model\OrdersModel;
use App\Model\ShopsModel;
use App\Utility\Alisms;
use App\Utility\ApiToken;
use App\Utility\ExcelClient;
use App\Utility\MiniProgram;
use App\Utility\Pool\MysqlObject;
use App\Utility\Pool\MysqlPool;
use easySwoole\Cache\Cache;
use EasySwoole\EasySwoole\ServerManager;


class IndexController extends ViewController{

    function index()
    {
        $request = $this->request();
        $id = $request->getRequestParam('id');
        $goods = MysqlPool::invoke(function (MysqlObject $db) use($id){
            $model  = new FoodsModel($db);
            $info = $model->find($id);
            //创建订单
            $insert = [
                'title' => $info['title'].'订单支付',
                'order_sn' => $this->buildOrderNo(),
                'money'  => $info['money'],
                'openid' => '12312312321213213213',
                'shopid' => $info['shopid'],
                'foodid' => $info['id'],
                'status' => OrdersModel::STATUS_1,
                'created_at' => date('Y-m-d')
            ];
            $orderModel  = new OrdersModel($db);
            $orderModel->create($insert);
            return ['food' => $info, 'order' => $insert];
        });

        return $this->render('index',compact('goods'));
    }

    public function sms(){
        try{
            $sms = new Alisms();
            $url = $sms->send('13667635645','SMS_163525395');
            return $this->writeJson(0,$url);
        }catch (\Throwable $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    public function excel(){
        $excel = new ExcelClient();
        $AResult = ['name','butotn','butotn2','butotnd'];
        //因为swoole有自己的response,header头不允许直接设置,其他框架可以直接用上一个函数
        $name = $excel->download($AResult);
        //生成文件后，使用response输出
        $this->response()->write(file_get_contents($name));
        $this->response()->withHeader('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $this->response()->withHeader('Content-Disposition', 'attachment;filename='.$name);
        $this->response()->withHeader('Cache-Control','max-age=0');
        $this->response()->end();
    }
}
